package com.example.config.dynamicTask;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ZhengDing
 * @date 2022/4/9 20:07
 */
@Component
@Slf4j
public class CronTaskRegistrar implements DisposableBean {
    
    // 定时任务调度器(线程池)
    @Resource
    TaskScheduler taskScheduler;
    
    // 任务管理池: 存的是 cronId:ScheduledFutureTask
    private final Map<Integer, ScheduledFutureTask> scheduledFutureTasks = new ConcurrentHashMap<>(16);
    
    // 添加定时任务
    public void addCronTask(Integer cronId, Runnable task, String cronExpression) {
        addCronTask(cronId, new CronTask(task, cronExpression));
    }
    
    // 移除定时任务
    public void removeCronTask(Integer cronId) {
        ScheduledFutureTask scheduledFutureTask = this.scheduledFutureTasks.remove(cronId);
        if (scheduledFutureTask != null) {
            log.info("移除定时任务 - [" + cronId + "] ");
            scheduledFutureTask.cancel();
        }
    }
    
    
    
    
    
    private void addCronTask(Integer cronId, CronTask cronTask) {
        if (cronTask != null) {
            if (this.scheduledFutureTasks.containsKey(cronId)) {
                removeCronTask(cronId);
                // String expression = cronTask.getExpression();
                // log.info("移除定时任务 - [" + cronId + "] " + expression);
            }
            log.info("新增定时任务 - [" + cronId + "] " + cronTask.getExpression());
            this.scheduledFutureTasks.put(cronId, scheduleCronTask(cronTask));
        }
    }
    
    private ScheduledFutureTask scheduleCronTask(CronTask cronTask) {
        ScheduledFutureTask scheduledFutureTask = new ScheduledFutureTask();
        scheduledFutureTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledFutureTask;
    }
    
    @Override
    public void destroy() throws Exception {
        for (ScheduledFutureTask task : this.scheduledFutureTasks.values()) {
            task.cancel();
        }
        this.scheduledFutureTasks.clear();
    }
    
    public TaskScheduler getScheduler() {
        return this.taskScheduler;
    }
}
